<?php
declare (strict_types=1);

namespace app\admin\controller;

use think\App;
use think\facade\View;
use think\response\Json;
use app\common\builder\TableBuilder;
use app\common\builder\TableFront;
use app\common\model\SpecItem;

class Spec extends Base
{
    //主键，默认为id
    protected $pk = 'id';

    //主模型
    protected $model = '\app\common\model\Spec';

    //验证器
    protected $validate = 'Spec';

    //关联模型
    protected $hasOne = ['cate1', 'cate2', 'cate3'];

    public function index()
    {

        return $this->setTable();
    }

    public function setTable()
    {
        //构建table
        $tableFront = TableFront::getInstance()
            ->addRow(['field' => 'id', 'sort' => true, 'title' => 'ID', 'width' => 80])
            ->addRow(['field' => 'key', 'title' => '规格名'])
            ->addRow(['field' => 'value', 'title' => '规格值'])
            ->addRow(['field' => 'cate', 'title' => '所属分类',
                      'templet' => '<div>{{d.cate1.title}} - {{d.cate2.title}} - {{d.cate3.title}}</div>'])
            ->addRow(['field' => 'create_time', 'title' => '创建时间'])
            ->addRow(['field' => 'update_time', 'title' => '更新时间'])
            ->addRow(['field' => 'status', 'title' => '状态', 'templet' => '#status', 'width' => 120, 'unresize' => true])
            ->addRow(['fixed' => 'right', 'align' => 'center', 'toolbar' => '#barDemo', 'title' => '操作', 'width' => 200]);

        return TableBuilder::getInstance()
            ->addColumns($tableFront)
            ->addTopButtons(['add' => ['width' => 900, 'height' => 1200], 'deleteAll'])
            ->addRightButtons(['edit' => ['width' => 900, 'height' => 1200], 'delete'])
            ->addSwitchTool([['name' => 'status', 'pk' => 'id', 'text' => '开启|关闭']])
            ->setSearch($this->setSearch())
            ->fetch();
    }

    public function setSearch()
    {
        return TableFront::getInstance()
            ->setSearch(['key__value', '输入规格名/规格值', 'input', '', '', '', 'like'])
            ->setSearch(['cate_1,cate_2', '一级分类,二级分类', 'linkage', url('productCate/getCate')->build()]);
    }


    public function add($name = '', $tpl = 'spec/edit')
    {
        return parent::add($name, $tpl); // TODO: Change the autogenerated stub
    }

    public function edit($name = '', $id = '', $tpl = 'spec/edit', $info = '')
    {
        View::assign('item', SpecItem::where('spec_id', $id)->select());
        return parent::edit($name, $id, $tpl, $info); // TODO: Change the autogenerated stub
    }


    public function save($param = [], $model = true): Json
    {
        return parent::save($param, $model); // TODO: Change the autogenerated stub
    }

    public function getSpec()
    {
        $param = $this->request->get();
        $business_id = !empty($param['business_id']) ? $param['business_id'] : 0;
        return json($this->model::getSpec($param['id'], 'cate_3', $param['pid'],$business_id));
    }

}
